##########################################################################################

library(dplyr)
library(data.table)
library(optparse)
library(reshape)

##########################################################################################

option_list <- list(
    make_option(c("--class"), type = "character") ,
    make_option(c("--smg_file"), type = "character") ,
    make_option(c("--sig_file"), type = "character") ,
    make_option(c("--mutRate_file"), type = "character") ,
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    class <- "cancer"
    sig_file <- "~/20220915_gastric_multiple/dna_combine/mutsig/cancer/sig_genes.txt"
    mutRate_file <- "~/20220915_gastric_multiple/dna_combine/images/mutRate/MutRate.tsv"
    smg_file <- "~/20220915_gastric_multiple/dna_combine/public_ref/SMG_sort.list"
    out_path <- "~/20220915_gastric_multiple/dna_combine/mutsig_check"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

class <- opt$class
sig_file <- opt$sig_file
smg_file <- opt$smg_file
mutRate_file <- opt$mutRate_file
out_path <- opt$out_path

dir.create(out_path , recursive = T)

###########################################################################################

dat_sig <- data.frame(fread(sig_file))
dat_mutRate <- data.frame(fread(mutRate_file))
dat_smg <- data.frame(fread(smg_file , header = F))

###########################################################################################

dat_sig <- data.frame( gene = dat_sig$gene , q = dat_sig$q )
dat_sig <- subset(dat_sig , q < 0.2)

###########################################################################################
## 突变率
dat_mutRate_tmp <- subset( dat_mutRate , Hugo_Symbol %in% dat_sig$gene )
dat_mutRate_tmp <- dat_mutRate_tmp[,c("Hugo_Symbol" , "Class" , "MutRate")]
dat_mutRate_tmp <- cast(dat_mutRate_tmp , Hugo_Symbol~Class)
dat_mutRate_tmp$Type <- class
dat_mutRate_tmp$report <- ifelse( dat_mutRate_tmp$Hugo_Symbol %in% dat_smg$V1 , TRUE , FALSE )

out_name <- paste0( out_path , "/mutRate.",class,".tsv" )
write.table( dat_mutRate_tmp , out_name , row.names = F , sep = '\t' , quote = F  )
